package com.huffman.smart_picture.common.auth.aspect;

import com.huffman.smart_picture.common.auth.AuthConstant;
import com.huffman.smart_picture.common.auth.annotation.CheckRole;
import com.huffman.smart_picture.common.UserSession;
import com.huffman.smart_picture.common.exception.BusinessException;
import com.huffman.smart_picture.common.exception.ErrorEnum;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @author DengLin
 * @title 登录权限校验
 * @date 2024/06/28
 */
@Component
@Aspect
@Slf4j
public class AuthAspect {


    @Pointcut("@annotation(com.huffman.smart_picture.common.auth.annotation.CheckRole)")
    public void authPt() {
    }

    @Before("authPt()")
    public void checkAuth(JoinPoint joinPoint) {
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        UserSession userSession = (UserSession) httpServletRequest.getSession().getAttribute(AuthConstant.LOGIN_USER);
        if (userSession == null) {
            throw new BusinessException(ErrorEnum.AUTHENTICATION_FAIL, "请求失败", "未登录");
        }
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        CheckRole checkRole = method.getAnnotation(CheckRole.class);
        String[] roles = checkRole.roles();
        if (roles.length == 0) {
            return;
        }
        if (!Arrays.asList(roles).contains(userSession.getRole())) {
            throw new BusinessException(ErrorEnum.AUTHENTICATION_FAIL, "请求失败", "该用户没有权限");
        }

    }

    @Pointcut("@annotation(com.huffman.smart_picture.common.auth.annotation.LoginRequired)")
    public void loginRequiredPt() {
    }

    @Before("loginRequiredPt()")
    public void loginRequired(JoinPoint joinPoint) {
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        UserSession userSession = (UserSession) httpServletRequest.getSession().getAttribute(AuthConstant.LOGIN_USER);
        if (userSession == null) {
            throw new BusinessException(ErrorEnum.AUTHENTICATION_FAIL, "请求失败", "未登录");
        }
    }

}
